/*
 * Copyright (C) 2017 zhouyou(478319399@qq.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.shuyihui.rxhttp.interceptor

import android.content.Context
import android.text.TextUtils
import com.shuyihui.rxhttp.utils.HttpLog
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 *
 * 描述：设置缓存功能
 */
open class CacheInterceptor(
    protected var context: Context?,
    protected var cacheControlValue_Offline: String?,
    protected var cacheControlValue_Online: String
) : Interceptor {
    @JvmOverloads
    constructor(
        context: Context?,
        cacheControlValue: String? = String.format("max-age=%d", maxStaleOnline)
    ) : this(context, cacheControlValue, String.format("max-age=%d", maxStale)) {
    }

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        //Request request = chain.request();
        val originalResponse: Response = chain.proceed(chain.request())
        val cacheControl = originalResponse.header("Cache-Control")
        //String cacheControl = request.cacheControl().toString();
        HttpLog.e(maxStaleOnline.toString() + "s load cache:" + cacheControl)
        return if (TextUtils.isEmpty(cacheControl) || cacheControl!!.contains("no-store") || cacheControl.contains(
                "no-cache"
            ) ||
            cacheControl.contains("must-revalidate") || cacheControl.contains("max-age") || cacheControl.contains(
                "max-stale"
            )
        ) {
            originalResponse.newBuilder()
                .removeHeader("Pragma")
                .removeHeader("Cache-Control")
                .header(
                    "Cache-Control",
                    "public, max-age=" + maxStale
                )
                .build()
        } else {
            originalResponse
        }
    }

    companion object {
        //set cahe times is 3 days
        protected const val maxStale = 60 * 60 * 24 * 3

        // read from cache for 60 s
        protected const val maxStaleOnline = 60
    }
}